/**
 * table 页面操作方法
 * 
 * @param {Function} getListApi 获取表格数据 api 方法 (必填)
 * @param {Object} initParam 获取数据初始化参数
 * @param {Boolean} isPageable 是否分页
 * @param {Function} successFn 获取列表数据成功回调
 * @param {Function} failFn 获取列表数据失败回调
 */
export const useTable = (
  getListApi,
  initParam = {},
  isPageable = true,
  successFn,
  failFn
) => {
  const state = reactive({
    tableData: [],
    pager: {
      curPageNum: 1,
      pageSize: 20,
      totalCount: 0
    },
    // 查询参数
    searchParam: {},
    // 请求参数
    requestParam: {}
  })

  /**
   * 获取表格数据
   */
  const getTableList = async () => {
    if (!getListApi) return
    try {
      state.requestParam = {}
      Object.assign(state.requestParam, initParam, state.searchParam, isPageable ? { pager: state.pager } : {})
      let { data, pager } = await getListApi(state.requestParam)
      successFn && (data = successFn(data))
      state.tableData = isPageable ? data.list : data
      if (isPageable) {
        Object.assign(state.pager, pager)
      }
    } catch (error) {
      failFn && failFn(error)
    }
  }

  /**
   * 表格数据查询
   */
  const search = () => {
    state.pager.curPageNum = 1
    getTableList()
  }

  /**
   * 表格数据重置
   */
  const reset = () => {
    state.searchParam = {}
    search()
  }

  /**
   * 每页条数改变
   * 
   * @param {Number} val 当前条数
   */
  const handleSizeChange = (val) => {
    state.pager.pageSize = val
    search()
  }

  /**
   * 当前页改变
   * 
   * @param {Number} val 当前页
   */
  const handleCurrentChange = (val) => {
    state.pager.curPageNum = val
    getTableList()
  }

  return {
    ...toRefs(state),
    getTableList,
    search,
    reset,
    handleSizeChange,
    handleCurrentChange
  }
}